package com.group.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.group.entity.ProjectOutside;
import com.group.entity.Talents;
import com.group.entity.User;
import com.group.mapper.TalentsMapper;
import com.group.mapper.UserMapper;
import com.group.service.ProjectOutsideService;
import com.group.service.TalentsService;
import com.group.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Random;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 朋心合力
 * @since 2021-08-09
 */
@Controller
//@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    @Autowired
    UserMapper userMapper;

    @Autowired
    ProjectOutsideService projectOutsideService;

    @Autowired
    TalentsService talentsService;

    @Autowired
    TalentsMapper talentsMapper;

    @GetMapping("/{url}")
    public String redirect(@PathVariable("url") String url) {
        return url;
    }


    @RequestMapping("/toLogin")
    public String toLogin() {
        return "login";
    }


    @RequestMapping("/login")
    public String login(String userName, String passWord, Model model, HttpSession session) {
        //获得当前的用户
        Subject subject = SecurityUtils.getSubject();
        //封装用户的登录数据
        UsernamePasswordToken token = new UsernamePasswordToken(userName, passWord);
        //执行登陆方法，如果没异常，则ok
        try {
            subject.login(token);
            QueryWrapper wrapper = new QueryWrapper();
            wrapper.eq("userName", userName);
            User currentUser = userService.getOne(wrapper);
            Integer currentUserId = currentUser.getUserId();
            session.setAttribute("currentUserId", currentUserId);
            if (currentUser.getPersonalName() == null) {
                return "login_moreinformation";
            } else {
                return "index";
            }
        } catch (UnknownAccountException e) {//用户名不存在
            model.addAttribute("msg", "用户名错误");
            return "login";
        } catch (IncorrectCredentialsException ice) {//密码错误
            model.addAttribute("msg", "密码错误");
            return "login";
        }

    }

    @PostMapping("/fillMoreInformation")
    public String fillMoreInformation(@RequestParam("talentTag") String[] talentTag,
                                      @RequestParam("talentAge") Integer talentAge,
                                      @RequestParam("personalName") String personalName,
                                      @RequestParam("talentIntro") String talentIntro,
                                      HttpSession session) {
        //获取登录的用户Id
        Integer currentUserId = (Integer) session.getAttribute("currentUserId");
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("userId", currentUserId);
        Talents talents = new Talents();
        User user = new User();
        talents.setUserId(currentUserId);
        talents.setTalentAge(talentAge);
        talents.setTalentIntro(talentIntro);
        talents.setTalentName(personalName);
        String talentTags = StringUtils.join(talentTag, ",");
        talents.setTalentTag(talentTags);
        talentsService.save(talents);
        user.setUserId(currentUserId);
        user.setPersonalName(personalName);
        userMapper.updateById(user);
        return "redirect:/userInformation";
    }

    //注销
    @RequestMapping("/logout")
    public String logout(HttpSession session) {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "redirect:/toLogin";
    }

    @RequestMapping("/registerUser")
    @ResponseBody
    public Integer register(String userName, String passWord, Model model) {
        boolean result = false;
        Integer i = 0;
        try {
            User user = new User();
            user.setUserName(userName);
            user.setPassWord(passWord);
            result = userService.save(user);
        } catch (Exception exception) {
            model.addAttribute("error", "用户名:" + userName + "已经存在!");
            return i;
        }
        if (result) {
            i = 1;
            return i;
        }
        return i;
    }


    @RequestMapping("/lookprojectsByTags")
    @ResponseBody
    public List<ProjectOutside> lookProjectsByTags(HttpServletRequest request, @RequestParam("zone") String[] zone) {
        StringBuffer sb = new StringBuffer();
        List<ProjectOutside> projectOutsides = null;
        if (zone.length == 1) {
            projectOutsides = projectOutsideService.find(zone[0], null);
        }
        if (zone.length == 2) {
            projectOutsides = projectOutsideService.find(zone[0], zone[1]);
        }
        if (zone.length == 3) {
//            projectOutsides = projectOutsideService.find(zone[0],zone[1],zone[2]);
        }
        projectOutsides.forEach(System.out::println);
        return projectOutsides;
    }

    @PostMapping("/usr/pwd")
    @ResponseBody
    public String modifyPassWordByCheck(@RequestParam(value = "oldPassword", required = true) String oldPassword, HttpSession session) {
        //拿到当前登录用户的Id
        Integer currentUserId = (Integer) session.getAttribute("currentUserId");
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("userId", currentUserId);
        User user = userService.getOne(wrapper);
        if (user.getPassWord().equals(oldPassword)) {
            return "true";
        } else {
            return "false";
        }
    }

    @PostMapping("/usr/updatePwd")

    @ResponseBody
    public String updatePwd(@RequestParam String newPassword, HttpSession session) {
        User user = new User();
        Integer currentUserId = (Integer) session.getAttribute("currentUserId");
        user.setPassWord(newPassword);
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("userId", currentUserId);
        boolean isSuccess = userService.update(user, wrapper);
        if (isSuccess) {
            return "update success";
        } else {
            return "update failure";
        }
    }


    @GetMapping("/userInformation")
    public String userInformation(HttpSession session, Model model) {
        Integer currentUserId = (Integer) session.getAttribute("currentUserId");
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("userId", currentUserId);
        User userInformation = userService.getOne(wrapper);
        model.addAttribute("userInformation", userInformation);
        Talents talentInformation = talentsService.getOne(wrapper);
        model.addAttribute("talentInformation", talentInformation);
        return "My_Ziliao";
    }

    //忘记密码
    @RequestMapping("/forget")
    @ResponseBody
    public String forget(String userName) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("userName", userName);
        User user = userService.getOne(wrapper);
        Random random = new Random();
        String newPwd = "";
        for (int i = 0; i < 6; i++) {
            newPwd += random.nextInt(10);
        }
        user.setPassWord(newPwd);
        userMapper.updateById(user);
        return newPwd;
    }
}

